// miniprogram/pages/auth/auth.js

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    logged: false,
    userInfo: {},
    openid: '',
    unionid: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo
              })
            }
          })
        }
      }
    })
  },

  onGetUserInfo: function (e) {
    console.log(e);
    if (!this.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        userInfo: e.detail.userInfo
      })

      // 获取openId
      this.onGetOpenid();

    }
  },

  onGetOpenid: function () {
    // 调用云函数
    let that = this;
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log(res);
        console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid;
        that.setData({
          openid: res.result.openid,
          unionid: res.result.unionid || ''
        })

        that.onQuery(res.result.openid);
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },

  // 查询
  onQuery: function (id) {
    let that = this;
    const db = wx.cloud.database();
    db.collection('users').where({
      openid: id
    }).get({
      success: res => {
        console.log('[数据库] [查询记录] 成功: ', res);
        if (res.data.length === 0) {
          that.addUsers();
        }
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/list/list'
          })
        })
      },
      fail: err => {
        console.error('[数据库] [查询记录] 失败：', err)
      }
    })
  },

  // 新增
  addUsers() {
    Object.assign(this.data.userInfo, { openid: this.data.openid, unionid: this.data.unionid });
    const db = wx.cloud.database();
    db.collection('users').add({
      data: this.data.userInfo,
      success: res => {
        this.setData({
          categoryId: res._id,
        })
        console.error('[数据库] [新增记录] 失败：', err);
      },
      fail: err => {
        console.error('[数据库] [新增记录] 失败：', err);
      },
      complete: () => {
        this.setData({
          disabled: false
        })
      }
    });
  },

})